package org.example.javaee.model;
import java.sql.*;

public class DBtext {

    String name;
    String pass;

    public void setInfo(String username,String password){
        this.name=username;
        this.pass=password;

    }



    public void userLogin() {
        String url = "jdbc:mysql://localhost:3306/library_mangement?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String user = "root";
        String password = "wyf050925";
        // 修正SQL语句中的拼写错误：possword -> password
        String sql = "select * from user where username=? and password=?";
        int Id = 0;
        String email = null;
        ResultSet rs = null;
        PreparedStatement prep = null ;
        Connection conn = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);

            prep = conn.prepareStatement(sql);
            prep.setString(1, name);
            prep.setString(2, pass);
            // 直接获取执行查询后的结果集
            rs = prep.executeQuery();

            while(rs.next()){
                Id = rs.getInt("id");
                email = rs.getString("email");
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源时先检查是否为null，避免空指针异常
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                System.out.println("rs关闭失败");
                throw new RuntimeException(e);
            }
            try {
                if (prep != null) {
                    prep.close();
                }
            } catch (SQLException e) {
                System.out.println("prep关闭失败");
                throw new RuntimeException(e);
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                System.out.println("conn关闭失败");
                throw new RuntimeException(e);
            }
        }

        System.out.println(Id);
        System.out.println(email);
    }
}